from rest_framework import views
from .. import models
from rest_framework import serializers
from rest_framework import response


class BookSerializer(serializers.ModelSerializer):
    title = serializers.CharField(error_messages={"max_length": "too long"}, max_length=12)

    class Meta:
        model = models.Book
        # fields = "__all__"
        fields = (
            "title",
        )
        # errors_messages = {
        #     "title" : {
        #         "max_length":"长于12个字符"
        #     }
        # }


class BookView(views.APIView):

    def get(self, request):
        qs = models.Book.objects.all()
        serializer = BookSerializer(qs, many=True)
        return response.Response({
            "code": 0,
            "data": serializer.data
        })

    def post(self, request):
        serializer = BookSerializer(data=request.data)
        if serializer.is_valid():
            instance = serializer.save()
            return response.Response({
                "code": 0,
                "data": instance.pk
            })
        else:
            return response.Response({
                "code": 1,
                "data": serializer.errors
            })


class BookDetailView(views.APIView):

    def put(self, request, pk):
        instance = models.Book.objects.filter(pk=pk).first()
        if not instance:
            return response.Response({
                "code": 1,
                "data": "数据不存在"
            })
        serializer = BookSerializer(instance=instance, data=request.data)
        if serializer.is_valid():
            instance = serializer.save()
            return response.Response({
                "code": 0,
                "data": instance.pk
            })
        else:
            return response.Response({
                "code": 1,
                "data": serializer.errors
            })

    def delete(self,request , pk):
        instance = models.Book.objects.filter(pk=pk).delete()
        return response.Response({
            "code": 0,
            "data": []
        })
